<?php
namespace App\Http\Controllers\Admin;
use App\Models\Admin\TvmMobileDetail;
use App\Models\Admin\TvmMobileCategory;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\Admin\capital;
use App\Models\Admin\transfer;
use App\Models\Admin\transfer_operator;



class CapitalController extends CommonController {

	public function __construct()
	{
		parent::__construct();
		$this->checkLogin();
	}





	/**
	 * 账户资金流水
	 **/
	public function capital_flow(Request $request) {
		
		$condition = array();
		$outownerid = $request->input('outownerid');
		if(!empty($outownerid)){
			$condition[] = ['out_owner_id','=',$outownerid];
		}

		$out_owner_type = $request->input('out_owner_type');
		if(!empty($out_owner_type)){
			$out_owner_type = explode('_', $out_owner_type);
		}
		if(!empty($out_owner_type)){
			$condition[] = ['out_owner_type','=',$out_owner_type[0]];
		}
		$outpurseid = $request->input('outpurseid');
		if(!empty($outpurseid)){
			$condition[] = ['out_purse_id','=',$outpurseid];
		}

		
		$outpursetype = $request->input('outpursetype');
		if(!empty($outpursetype)){
			$outpursetype = explode('_', $outpursetype);
		}

		if(!empty($outpursetype)){
			$condition[] = ['p.pursetype','=',$outpursetype[0]];
		}

		$intopursetype = $request->input('intopursetype');
		if(!empty($intopursetype)){
			$intopursetype = explode('_', $intopursetype);
		}
		if(!empty($intopursetype)){
			$condition[] = ['u.pursetype','=',$intopursetype[0]];
		}
		

		$into_owner_type = $request->input('into_owner_type');
		if(!empty($into_owner_type)){
			$into_owner_type = explode('_', $into_owner_type);
		}
		if(!empty($into_owner_type)){
			$condition[] = ['into_owner_type','=',$into_owner_type[0]];
		}

		$intopurseid = $request->input('intopurseid');
		if(!empty($intopurseid)){
			$condition[] = ['into_purse_id','=',$intopurseid];
		}

		$intoownerid = $request->input('intoownerid');
		if(!empty($intoownerid)){
			$condition[] = ['into_owner_id','=',$intoownerid];
		}

		
		$transfer_id = $request->input('transfer_id');
		if(!empty($transfer_id)){
			$condition[] = ['transfer_id','=',$transfer_id];
		}

		$reason = $request->input('reason');
		if(!empty($reason)){
			$condition[] = ['reason','=',$reason];
		}

		// $user = DB::select('select * from tblc_transfer t left join tnet_reginfo r on t.out_owner_id = r.nodeid');
		// dd($user);
		
		//转账资金流水
			$data = DB::table('tblc_transfer t')
				->leftJoin('tnet_reginfo r', 't.out_owner_id', '=', 'r.nodeid')
				->leftJoin('tnet_reginfo i', 't.into_owner_id', '=', 'i.nodeid')
				->leftJoin('tblc_user_purse p', 't.out_purse_id', '=', 'p.purseid')
				->leftJoin('tblc_user_purse u', 't.into_purse_id', '=', 'u.purseid')
				->leftJoin('tblc_currency c', 'p.currencytype', '=', 'c.currencyid')
				->leftJoin('tblc_transfer_reson s', 't.reason', '=', 's.reson_code')
				->select('t.transfer_id','t.reason','t.out_amount','t.out_purse_id','t.remarks','t.create_time','t.into_amount','t.status',
						 't.out_owner_id','t.out_owner_type','t.into_owner_type','t.into_purse_id','t.into_owner_id','c.currency_unit',
						 DB::raw('i.nodename as into_nodename'),DB::raw('i.nodecode as into_nodecode'),
						 DB::raw('r.nodename as out_nodename'),
						 DB::raw('r.nodecode as out_nodecode'),'s.reson_name',
						 DB::raw('p.pursetype as outpursetype'),DB::raw('u.pursetype as intopursetype'))
				->orderBy('t.transfer_id', 'DESC')
				->where($condition)
		        ->paginate(15);
			// dd($data);
		 // $data = DB::table('tblc_transfer')->orderBy('out_amount','desc')->where($condition)->paginate(15);
			// foreach ($data as $key => &$value) {
			// 	//转出者账号姓名
			// 	$outuser = DB::table('tnet_reginfo')->select('nodename','nodecode')->where('nodeid',$value->out_owner_id)->first();

			// 	//转入者账号姓名
			// 	$intouser = DB::table('tnet_reginfo')->select('nodename','nodecode')->where('nodeid',$value->into_owner_id)->first();
			// 	//转出者账号姓名
			// 	if(!empty($outuser)){
			// 		$value->out_nodename = $outuser->nodename;
			// 		$value->out_nodecode = $outuser->nodecode;
			// 	}else{
			// 		$value->out_nodename = '';
			// 		$value->out_nodecode = '';
			// 	}
				
			// 	//转入者账号姓名
			// 	if(!empty($intouser)){
			// 		$value->into_nodename = $intouser->nodename;
			// 		$value->into_nodecode = $intouser->nodecode;
			// 	}else{
			// 		$value->into_nodename = '';
			// 		$value->into_nodecode = '';
			// 	}
			// 	//转出者账户类型
			// 	$outpursetype = DB::table('tblc_user_purse')->select('pursetype','currencytype')->where('purseid',$value->out_purse_id)->first();
			// 	//转账金额单位
			// 	$currency = DB::table('tblc_currency')->select('currency_unit')->where('currencyid',$outpursetype->currencytype)->first();
			// 	//转入者账户类型
			// 	$intopursetype = DB::table('tblc_user_purse')->select('pursetype')->where('purseid',$value->into_purse_id)->first();
			// 	if(!empty($outpursetype)){
			// 		$value->outpursetype = $outpursetype->pursetype;
			// 	}else{
			// 		$value->outpursetype = '';
			// 	}

			// 	if(!empty($intopursetype)){
			// 		$value->intopursetype = $intopursetype->pursetype;
			// 	}else{
			// 		$value->intopursetype = '';
			// 	}

				
			// 	//转账金额单位
			// 	$value->currency_unit = $currency->currency_unit;
				
			// 	//转账原因
			// 	$reson = DB::table('tblc_transfer_reson')->select('reson_name')->where('reson_id',$value->reason)->first();
			// 	if(!empty($reson)){
			// 		$value->reson_name = $reson->reson_name;
			// 	}else{
			// 		$value->reson_name = '';
			// 	}
				
				
			// }
			$data->appends($request->all());
		//展示模板
		return view('admin.capital.capital_flow',[
			'data' => $data,
			'outpursetype' => $outpursetype[1],
			'out_owner_id' => $outownerid,
			'out_purse_id' => $outpurseid,
			'out_owner_type' => $out_owner_type[1],
			'into_owner_type' => $into_owner_type[1],
			'into_purse_id' => $intopurseid,
			'into_owner_id' => $intoownerid,
			'intopursetype' => $intopursetype[1],
			'reason' => $reason,
			'transfer_id' => $transfer_id
		]);
	}

	/**
	 * 流水冲账
	 **/
	public function water_off(Request $request) {
		     	$transfer_id = $request->input('transfer_id');
		    	if($request->isMethod('post')){
		    	$transfer_id = $request->input('transfer_id');
				$remarks = $request->input('remarks');
				if($transfer_id){
					
					$res = $this->common_method($transfer_id);
					// dd($res);
					//dd($res);
					if($res[0]->status==1){
						$this->ajax_error('退款失败1.该笔流水不支持冲正[当前状态：冲正记录] {错误代码:0 未指定}');
					}
					if($res[0]->status==2){
						$this->ajax_error('退款失败1.该笔流水不支持冲正[当前状态：已被冲正] {错误代码:0 未指定}');
					}
					$update['status'] = 2;
					DB::table('tblc_transfer')->where('transfer_id',$transfer_id)->update($update);
					//生成一条新的账户流水记录
					$data = array(
						'transfer_id' => Transfer::getNextSeq(),
						'out_owner_id'=>$res[0]->into_owner_id,
						'out_owner_type'=>$res[0]->into_owner_type,
						'into_owner_id'=>$res[0]->out_owner_id,
						'into_owner_type'=>$res[0]->out_owner_type,
						'out_amount'=>$res[0]->out_amount,
						'remarks'=>$remarks,
						'reason'=>16,
						'out_purse_id'=>$res[0]->into_purse_id,
						'into_purse_id'=>$res[0]->out_purse_id,
						'into_amount'=>$res[0]->out_amount,
						'status'=>1,
						'create_time' => date('Y-m-d H:i:s',time()),



					);
					$insert_id = DB::table('tblc_transfer')->insertGetId($data,'transfer_id');
					//插入日志
					$insert = array(
					'refund_id' => Capital::getNextSeq(),
					'refund_transfer_id' => $transfer_id, //被冲正流水号
					/*
					冲正流水号暂时不知道从哪里来，先默认同上
					 */
					'transfer_id' => $insert_id, //冲正流水号
					'op_node_id' => $_SESSION['admin_uid'], //操作员ID
					'create_time' =>date('Y-m-d H:i:s',time()), //时间
					'remark' => $remarks, //锁定备注
					);
					Db::table('tblc_refund_his')->insert($insert);
					$this->ajax_success('操作成功');
					
				}else{
					$this->ajax_error('操作失败');
				}
			
		
		}
				//展示模板
				return view('admin.capital.water_off',[
				 'action'=>'water_off',
				 'transfer_id'=>$transfer_id
				]);
	}

	/*流水冲正日志*/
	public function water_log(Request $request) {
			$condition = array();
			if($request->input('refund_transfer_id')){
				$condition[] = ['refund_transfer_id','=',$request->input('refund_transfer_id')];
			}
			if($request->input('transfer_id')){
				$condition[] = ['transfer_id','=',$request->input('transfer_id')];
			}
			//查询冲正日志
			$data = DB::table('tblc_refund_his h')
			->leftJoin('tnet_reginfo r', 'h.op_node_id', '=', 'r.nodeid')
			->select('h.refund_id','h.op_node_id','h.refund_transfer_id','h.transfer_id','h.remark','h.create_time','r.nodecode','r.nodename')
			->where($condition)
			->orderBy('h.refund_id','DESC')
			->paginate(10);
			//展示模板
		   return view('admin.capital.water_log',[
		  		'data'=>$data
		  	]);
	}
	/**
	 * 被冲正流水信息
	 **/
	public function cover_water(Request $request) {
			$condition = array();
			$refund_transfer_id = $request->input('refund_transfer_id');
			$condition[] = ['transfer_id','=',$refund_transfer_id];
			//被冲正流水信息
			$data = DB::table('tblc_transfer')->orderBy('out_amount','desc')->where($condition)->get();
			// dd($data);
			// dd($data);
			foreach ($data as $key => &$value) {
				//转出者账号姓名
				$outuser = DB::table('tnet_reginfo')->select('nodename','nodecode')->where('nodeid',$value->out_owner_id)->first();

				//转入者账号姓名
				$intouser = DB::table('tnet_reginfo')->select('nodename','nodecode')->where('nodeid',$value->into_owner_id)->first();
				//转出者账号姓名
				if(!empty($outuser)){
					$value->out_nodename = $outuser->nodename;
					$value->out_nodecode = $outuser->nodecode;
				}else{
					$value->out_nodename = '';
					$value->out_nodecode = '';
				}
				
				//转入者账号姓名
				if(!empty($intouser)){
					$value->into_nodename = $intouser->nodename;
					$value->into_nodecode = $intouser->nodecode;
				}else{
					$value->into_nodename = '';
					$value->into_nodecode = '';
				}
				//转出者账户类型
				$outpursetype = DB::table('tblc_user_purse')->select('pursetype','currencytype')->where('purseid',$value->out_purse_id)->first();
				//转账金额单位
				$currency = DB::table('tblc_currency')->select('currency_unit')->where('currencyid',$outpursetype->currencytype)->first();
				//转入者账户类型
				$intopursetype = DB::table('tblc_user_purse')->select('pursetype')->where('purseid',$value->into_purse_id)->first();
				if(!empty($outpursetype)){
					$value->outpursetype = $outpursetype->pursetype;
				}else{
					$value->outpursetype = '';
				}

				if(!empty($intopursetype)){
					$value->intopursetype = $intopursetype->pursetype;
				}else{
					$value->intopursetype = '';
				}

				
				//转账金额单位
				$value->currency_unit = $currency->currency_unit;
				
				//转账原因
				$reson = DB::table('tblc_transfer_reson')->select('reson_name')->where('reson_id',$value->reason)->first();
				if(!empty($reson)){
					$value->reson_name = $reson->reson_name;
				}else{
					$value->reson_name = '';
				}
				
				
			}
		//展示模板
        return view('admin.capital.cover_water',['data'=>$data]);
	}

	/*人工转账日志*/
	public function transfer_log(Request $request) {
			$condition = array();
			if($request->input('transfer_id')){
				$condition[] = ['transfer_id','=',$request->input('transfer_id')];
			}
			if($request->input('nodecode')){
				$condition[] = ['nodecode','=',$request->input('nodecode')];
			}
			//查询转账日志
			$data = DB::table('tblc_transfer_operator h')
			->leftJoin('tnet_reginfo r', 'h.node_id', '=', 'r.nodeid')
			->select('h.operator_id','h.transfer_id','h.remarks','h.createtime','r.nodecode','r.nodename')
			->where($condition)
			->orderBy('h.operator_id','DESC')
			->paginate(10);
			//展示模板
		   return view('admin.capital.transfer_log',[
		  		'data'=>$data
		  	]);
	}
	/**
	 * 人工转账日志详情
	 **/
	public function transfer_log_detail(Request $request) {
			$condition = array();
			$transfer_id = $request->input('transfer_id');
			$condition[] = ['transfer_id','=',$transfer_id];
			//被冲正流水信息
			$data = DB::table('tblc_transfer')->orderBy('out_amount','desc')->where($condition)->get();
			// dd($data);
			// dd($data);
			foreach ($data as $key => &$value) {
				//转出者账号姓名
				$outuser = DB::table('tnet_reginfo')->select('nodename','nodecode')->where('nodeid',$value->out_owner_id)->first();

				//转入者账号姓名
				$intouser = DB::table('tnet_reginfo')->select('nodename','nodecode')->where('nodeid',$value->into_owner_id)->first();
				//转出者账号姓名
				if(!empty($outuser)){
					$value->out_nodename = $outuser->nodename;
					$value->out_nodecode = $outuser->nodecode;
				}else{
					$value->out_nodename = '';
					$value->out_nodecode = '';
				}
				
				//转入者账号姓名
				if(!empty($intouser)){
					$value->into_nodename = $intouser->nodename;
					$value->into_nodecode = $intouser->nodecode;
				}else{
					$value->into_nodename = '';
					$value->into_nodecode = '';
				}
				//转出者账户类型
				$outpursetype = DB::table('tblc_user_purse')->select('pursetype','currencytype')->where('purseid',$value->out_purse_id)->first();
				//转账金额单位
				$currency = DB::table('tblc_currency')->select('currency_unit')->where('currencyid',$outpursetype->currencytype)->first();
				//转入者账户类型
				$intopursetype = DB::table('tblc_user_purse')->select('pursetype')->where('purseid',$value->into_purse_id)->first();
				if(!empty($outpursetype)){
					$value->outpursetype = $outpursetype->pursetype;
				}else{
					$value->outpursetype = '';
				}

				if(!empty($intopursetype)){
					$value->intopursetype = $intopursetype->pursetype;
				}else{
					$value->intopursetype = '';
				}

				
				//转账金额单位
				$value->currency_unit = $currency->currency_unit;
				
				//转账原因
				$reson = DB::table('tblc_transfer_reson')->select('reson_name')->where('reson_id',$value->reason)->first();
				if(!empty($reson)){
					$value->reson_name = $reson->reson_name;
				}else{
					$value->reson_name = '';
				}
				
				
			}
		//展示模板
        return view('admin.capital.transfer_log_detail',['data'=>$data]);
	}


	/**
	 * 转出钱包页面
	 **/
	public function account_transfer(Request $request) {
		$id = $request->input('id');
		if($id){
			$condition[] = ['purseid','=',$id];
			$data = DB::table('tblc_user_purse t')
				->leftJoin('tnet_reginfo r', 't.ownerid', '=', 'r.nodeid')
				->leftJoin('tblc_currency c', 't.currencytype', '=', 'c.currencyid')
				->select('t.purseid','t.ownerid','t.pursetype','t.subid','t.balance',DB::raw('t.minvalue'),'t.ownertype',
						't.currencytype','t.hisid_last','t.status','t.create_time','t.freezevalue','r.nodeid','r.nodecode','r.nodename','c.currencyid','c.currency_type','c.currency_unit')
				->where($condition)
				->first();
		}else{
			$data = array();
		}
		//转账原因
		$resonlist = DB::table('tblc_transfer_reson')->get();
		//展示模板
	   return view('admin.capital.account_transfer',[
	  		'data'=>$data,
	  		'id'=>$id,
	  		'resonlist'=>$resonlist
	  	]);
	}

	/**
	 * 转入钱包页面
	 **/
	public function intoaccount_transfer(Request $request) {
		$id = $request->input('id');
		if($id){
			$condition[] = ['purseid','=',$id];
			$res = DB::table('tblc_user_purse t')
				->leftJoin('tnet_reginfo r', 't.ownerid', '=', 'r.nodeid')
				->leftJoin('tblc_currency c', 't.currencytype', '=', 'c.currencyid')
				->select('t.purseid','t.ownerid','t.pursetype','t.subid','t.balance',DB::raw('t.minvalue'),'t.ownertype',
						't.currencytype','t.hisid_last','t.status','t.create_time','t.freezevalue','r.nodeid','r.nodecode','r.nodename','c.currencyid','c.currency_type','c.currency_unit')
				->where($condition)
				->first();
		}else{
			$data = array();
		}
	//展示模板
	   return view('admin.capital.account_transfer',[
	  		'data'=>$res,
	  		'id'=>$id
	  	]);
	}

	/**
	 * 选择转出的钱包
	 **/
	public function choise_outmoney(Request $request) {
		$condition = array();
		$pursetype = $request->input('pursetype');
		if(!empty($pursetype)){
			$pursetype = explode('_', $pursetype);
		}
		$ownertype = $request->input('ownertype');
		if(!empty($ownertype)){
			$ownertype = explode('_', $ownertype);
		}

		$nodecode = $request->input('nodecode');
		if(!empty($nodecode)){
			$condition[] = ['nodecode','=',$nodecode];
		}
		$nodename = $request->input('nodename');
		if(!empty($nodename)){
			$condition[] = ['nodename','=',$nodename];
		}

		$purseid = $request->input('purseid');
		if(!empty($purseid)){
			$condition[] = ['purseid','=',$purseid];
		}

		
		if(!empty($pursetype)){
			$condition[] = ['pursetype','=',$pursetype[0]];
		}
		if(!empty($ownertype)){
			$condition[] = ['ownertype','=',$ownertype[0]];
		}
	
		
		
		//查询钱包列表
			$data = DB::table('tblc_user_purse t')
			->leftJoin('tnet_reginfo r', 't.ownerid', '=', 'r.nodeid')
			->leftJoin('tblc_currency c', 't.currencytype', '=', 'c.currencyid')
			->select('t.purseid','t.ownerid','t.pursetype','t.subid','t.balance',DB::raw('t.minvalue'),'t.ownertype',
					't.currencytype','t.hisid_last','t.status','t.create_time','t.freezevalue','r.nodeid','r.nodecode','r.nodename','c.currencyid','c.currency_type','c.currency_unit')
			->where($condition)
			->orderBy('t.balance','DESC')
			->paginate(10);
		//展示模板
		return view('admin.capital.choise_outmoneylist',[
			'data' => $data,
			'nodecode' => $nodecode,
			'nodename' => $nodename,
			'purseid' => $purseid,
			'ownertype' => $ownertype[1],
			'pursetype' => $pursetype[1]
		]);
	}
	/**
	 * 钱包转账
	 * @param int $from 转出钱包purseid
	 * @param int $to 转入钱包purseid
	 * @param float $amount 转账金额
	 * @param string $reason 转账原因
	 * @param string $detail 流水对应操作详情 表名:表ID
	 * @param string $remarks 备注
	 * @return boolean 是否转账成功
	 */
	
	public function doTransfer(Request $request) {
		$out_purse_id = $request->input('out_purse_id');//转出钱包编号
		$into_purse_id = $request->input('into_purse_id');//转入钱包编号
		$amount = $request->input('amount');//转账金额
		$reason = $request->input('reason');//转账原因ID
		$safety_code = $request->input('safety_code');//转账安全码
		//用户账号
		$nodecode = DB::table('tnet_reginfo')->where('nodeid',$_SESSION['admin_uid'])->value('nodecode');
		if(md5($safety_code) != md5($nodecode.'_'.date('Y-m-d',time()))){
			$this->ajax_error("安全码验证错误");
		}
		$remark = $request->input('remark');//转账备注

		if($amount <= 0){
			$this->ajax_error("转账金额小于等于0");
		}
		if($out_purse_id == $into_purse_id){
			$this->ajax_error("转出转入钱包相同!");
		}
		$outPurse = Db::table('tblc_user_purse')->where('purseid',$out_purse_id)->first();
		
		//filedebug('fromPurse','./log/doTransfer.php');
		//filedebug($fromPurse,'./log/doTransfer.php');

		$intoPurse = Db::table('tblc_user_purse')->where('purseid',$into_purse_id)->first();
		//filedebug('toPurse','./log/doTransfer.php');
		//filedebug($toPurse,'./log/doTransfer.php');

		if(!$outPurse && !$intoPurse){
			$this->ajax_error("转入或转出钱包不存在");
		}
		//如果钱包余额减去冻结金额小于转出的金额提示余额不足
		if($outPurse->balance - $intoPurse->freezevalue < $amount){
			$this->ajax_error("余额不足"); //转出者钱包余额不足[ID:$from]
		}
		if(!Db::table('tblc_transfer_reson')->where('reson_id' , $reason)->first()){
			$this->ajax_error("转账原因不存在!");
		}

		// 转出者减少余额
		$oR = Db::table('tblc_user_purse')->where("purseid",$out_purse_id)->decrement('balance' , $amount);
		if(!$oR){
			$this->ajax_error("转出者账号扣款失败!");
		}
		// 转入者增加余额
		$iR = Db::table('tblc_user_purse')->where("purseid",$into_purse_id)->increment('balance' , $amount);
		if(!$iR){
			$this->ajax_error("转入者账号收款失败!");
		}

		// 添加转账记录
		$transferCon = array(
			'transfer_id' => Transfer::getNextSeq(),
			'out_owner_id' => $outPurse->ownerid,
			'out_owner_type' => $outPurse->ownertype,
			'into_owner_id' => $intoPurse->ownerid,
			'into_owner_type' => $intoPurse->ownertype,
			'out_amount' => $amount,
			'out_purse_id' => $outPurse->purseid,
			'into_amount' => $amount,
			'into_purse_id' => $intoPurse->purseid,
			// 'out_balance' => $fromPurse['balance'] - $amount,
			// 'into_balance' => $toPurse['balance'] + $amount,
			//'detail' => $detail,
			'remarks' => $remark,
			'reason' => $reason,
			'create_time' => date('Y-m-d H:i:s',time()),
		);

		$transfer_id = Db::table('tblc_transfer')->insertGetId($transferCon,'transfer_id');
		if(!$transfer_id){
			$this->ajax_error("资金流水记录失败!");
		}
		// 添加转账日志
		$transferConLog = array(
			'operator_id' => Transfer_operator::getNextSeq(),
			'transfer_id' => $transfer_id,
			'node_id' => $_SESSION['admin_uid'],
			'remarks' => $remark,
			'createtime' => date('Y-m-d H:i:s',time()),
		);
		$operator_id = Db::table('tblc_transfer_operator')->insertGetId($transferConLog,'operator_id');
		if(!$operator_id){
			$this->ajax_error("转账日志记录失败!");
		}
		
		$this->ajax_success("转账成功!");

	}


}